<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\Request;
use think\facade\View;
use think\helper\Str;
use app\validate\CheckTopicRole;
use think\exception\ValidateException;


// 话题角色管理
class TopicRole extends BaseController
{
    public function index()
    {
        return View::fetch();
    }

    //+数据加载
    public function load(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();

        $where = [];
        if (isset($get['key'])) {
            if (!empty($get['key'])) {
                $where[] = ['name|remark', 'like', '%'.$get['key'].'%'];
            }
        }

        $list = Db::name('members_role')
            ->where($where)
            ->order('id', 'desc')
            ->select();

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => 0,
            'data'=> $list
        );
        return json($data);
    }


    public function add()
    {
        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        return View::fetch();
    }

    //+保存
    public function save(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();

        // 验证
        try {

            validate(CheckTopicRole::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }

        try {
            $data = array(
                'name'       => $post['name'],
                'remark' => $post['remark'],
                'add_time'    => time(),
            );
            if (!Db::name('members_role')->insert($data)) {
                return $this->outputAjax('操作失败！');
            }
            return $this->outputAjax('操作成功！',0);
        } catch (\Exception $e) {
                return $this->outputAjax($e->getMessage());
        }
    }

    /*
     * 修改
     */
    public function edit(Request $request)
    {
        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $id = $request->param('id');
        $inf = Db::name('members_role')->find($id);
        View::assign('inf',$inf);
        return View::fetch();
    }


    public function modify(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        $post = remove_xss($post);

        // 验证
        $validate = new \app\validate\CheckTopicRole;
        $result = $validate->check($post);

        if(!$result){
            return $this->outputAjax($validate->getError());
        }

        try {
            $update = array(
                'id'     => $post['id'],
                'name'   => $post['name'],
                'remark' => $post['remark'],
            );

            if (!Db::name('members_role')->update($update)) {
                return $this->outputAjax('操作失败！');
            }
            return $this->outputAjax('操作成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    public function delete(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');

        try {
            $where = array(
                'id' => $id
            );

            $inf = Db::name('members_role')->where($where)->find();

            if (!$inf) {
                return $this->outputAjax('参数错误！');
            }
            Db::startTrans();
            if (!Db::name('members_role')->where($where)->delete()) {
                Db::rollback();
                return $this->outputAjax('删除失败');
            }

            //+删除角色对应的员工
            $relation = Db::name('members_role_relation')->where('role_id', '=', $id)->find();
            if ($relation) {
                if (!Db::name('members_role_relation')->where('role_id', '=', $id)->delete()) {
                    Db::rollback();
                    return $this->outputAjax('删除失败[1]');
                }
            }

            //+删除角色对应的话题
            $role = Db::name('topic_role')->where('role_id', '=', $id)->find();
            if ($role) {
                if (!Db::name('topic_role')->where('role_id', '=', $id)->delete()) {
                    Db::rollback();
                    return $this->outputAjax('删除失败[2]');
                }
            }
            Db::commit();
            return $this->outputAjax('删除成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    public function members(Request $request)
    {
        $id = $request->param('id');
        View::assign('id',$id);
        return View::fetch();
    }


    //+分配用户加载
    public function getMembersList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();
        $id = $request->param('id');

        $total = Db::table('o_members_role_relation')
            ->alias('a')
            ->join('o_members b', 'b.id=a.uid','left')
            ->where('a.role_id', '=', $id)
            ->count();

        $rows = Db::table('o_members_role_relation')
            ->alias('a')
            ->join('o_members b', 'b.id=a.uid','left')
            ->where('a.role_id', '=', $id)
            ->field('b.userid, a.id ,b.name, b.mobile')
            ->page($get['page'], $get['limit'])
            ->select()->toArray();

        foreach ($rows as &$v){
            $count = mb_strlen($v['userid']);
            if ($count == 6) {
                if (is_numeric($v['userid'])) {
                    $v['userid'] = '00'.$v['userid'];
                }
            }
            if (empty($v['mobile'])) {
                $v['mobile'] = '';
            } else {
                $v['mobile'] = decrypts($v['mobile']);
            }
        }

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }


    // 学员
    public function user(Request $request)
    {
        $id = $request->param('id');
        View::assign('id',$id);
        return View::fetch();
    }



    //+员工数据加载
    public function getUserLoad(Request $request) {

        $get = $request->get();

        $field = 'id';
        $sort = 'asc';
        $where = [];

        if (isset($get['tree_select_nodeId'])) {
            if (!empty($get['tree_select_nodeId'])) {
                $department = $get['tree_select_nodeId'];
                $arr = get_children($department, 1);
                $arr[] = $department;
                $department = implode('|', $arr);
                $where[]  = ['', 'EXP', Db::raw("CONCAT(',',a.department,',') REGEXP concat(',(',replace('".$department."',',','|'),'),')")];
            }
        }


        if (isset($get['role'])) {
            if (!empty($get['role'])) {
                $where[] = ['a.role', '=', $get['role']];
            }
        }


        if (isset($get['key'])) {
            if (!empty($get['key'])) {
                $where[] = ['a.name|a.userid', 'like', '%'.$get['key'].'%'];
            }
        }

        $where[] = ['a.status', '<>', 3];


        $total = Db::table('o_members')
            ->alias('a')
            ->where($where)
            ->count();


        $rows = Db::table('o_members')
            ->alias('a')
            ->where($where)
            ->field('a.*')
            ->order($field, $sort)
            ->page($get['page'], $get['limit'])
            ->select()->toArray();

        foreach ($rows as &$v) {
            $count = mb_strlen($v['userid']);
            if ($count == 6) {
                if (is_numeric($v['userid'])) {
                    $v['userid'] = '00'.$v['userid'];
                }
            }
        }
        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }


    // 保存分配学员
    public function saveMembers(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');

        $user_id = $request->post('user_id');

        if(!$id){
            return $this->outputAjax('缺少角色id！');
        }

        try {

            $user_ids = explode(',',$user_id);

            if(!is_array($user_ids) || count($user_ids) <= 0){
                return $this->outputAjax('请选择学员！');
            }

            foreach ($user_ids as $key => $value) {
                $where = [];
                $user = Db::name('members')->where('id', '=', $value)->find();

                $where[] = ['role_id', '=', $id];
                $where[] = ['userid', '=', $user['userid']];
                $where[] = ['uid', '=', $user['id']];
                $res = Db::name('members_role_relation')->where($where)->find();
                if(!$res) {
                    $insert = array(
                        'role_id' => $id,
                        'userid' => $user['userid'],
                        'uid' => $user['id'],
                    );
                    Db::name('members_role_relation')->insert($insert);
                }
            }

            return $this->outputAjax('操作成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    //删除分配学员
    public function deleteMembers(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');

        if(!$id){
            return $this->outputAjax('请选择用户！');
        }

        try {
            if (!Db::name('members_role_relation')->where('id','in', $id)->delete()) {
                return $this->outputAjax('删除失败！');
            }
            return $this->outputAjax('删除成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

    // 分配话题
    public function topicType(Request $request)
    {
        $id = $request->param('id');
        View::assign('id',$id);
        return View::fetch();
    }

    // 话题加载
    public function getTopicTypeList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();
        $id = $request->param('id');

        $total = Db::table('o_topic_role')
            ->alias('a')
            ->join('o_topic_type b', 'a.topic_id = b.id','left')
            ->where('a.role_id', $id)
            ->count();

        $rows = Db::table('o_topic_role')
            ->alias('a')
            ->join('o_topic_type b', 'a.topic_id = b.id','left')
            ->where('a.role_id', $id)
            ->field('a.*,b.name,b.e_name')
            ->page($get['page'], $get['limit'])
            ->select();

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }


    // 新增话题
    public function type(Request $request)
    {
        $id = $request->param('id');
        View::assign('id',$id);
        return View::fetch();
    }

    //+话题加载
    public function getTypeList(Request $request)
    {
        $get = $request->get();

        $where = [
            'role' => 1,
            'status'=>1
        ];

        $total = Db::name('topic_type')
            ->where($where)
            ->count();

        $rows = Db::name('topic_type')
            ->where($where)
            ->order('sort asc')
            ->page($get['page'], $get['limit'])
            ->select();

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }

    // 保存话题
    public function saveType(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }
        $id = $request->post('id');

        $type_id = $request->post('type_id');

        if(!$id){
            return $this->outputAjax('缺少角色id！');
        }

        try {

            $type_ids = explode(',',$type_id);

            if(!is_array($type_ids) || count($type_ids) <= 0){
                return $this->outputAjax('请选择话题！');
            }

            foreach ($type_ids as $key => $value) {
                $where = [];

                $where[] = ['role_id', '=', $id];
                $where[] = ['topic_id', '=', $value];
                $res = Db::name('topic_role')->where($where)->find();
                if(!$res) {
                    $insert = array(
                        'role_id' => $id,
                        'topic_id' => $value,
                    );
                    Db::name('topic_role')->insert($insert);
                }
            }

            return $this->outputAjax('操作成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

    //删除话题
    public function deleteTopicType(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }
        $id = $request->post('id');

        if(!$id){
            return $this->outputAjax('请选择话题！');
        }

        try {
            if (!Db::name('topic_role')->where('id','in',$id)->delete()) {
                return $this->outputAjax('删除失败！');
            }
            return $this->outputAjax('删除成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }
}